package com.cwj.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cwj.common.domain.user;
import com.cwj.user.Listener.Beans;
import com.cwj.user.service.SignIn;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Service
public class SignInImpl implements SignIn {
    @Resource
    private com.cwj.user.dao.userDao userDao;
    @Resource
    private ServletContext servletContext;
    @Resource
    private Beans beans;
    @Resource
    private HttpSession session;
    @Override
    public Boolean isUserNameExit(String username) {
      user user = userDao.selectOne(new QueryWrapper<user>().eq("username",username));

        return user !=null;
    }
    @Transactional
    @Order(1)
    @Override
    public Boolean isSignIn(user user, MultipartFile headPhoto) throws IOException {

        user.setEmail("".equals(user.getEmail()) ? null : user.getEmail());
        String filename = headPhoto.getOriginalFilename();
        if(!"".equals(filename)){
            String photoPath = servletContext.getRealPath("headPhoto");
            File photo = new File(photoPath + "/" +user.getUsername()+filename.substring(filename.lastIndexOf(".")));
            headPhoto.transferTo(photo);
            user.setHeadPhoto(photo.getAbsolutePath().substring(beans.getServerPath().length()));
        }
        boolean b = userDao.insert(user) >= 1;
        if(b){
            session.setAttribute("user",user);
        }
        return b;
    }
}
